package com.yu.util;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class HttpUtils {

	private static NameValuePair basicNameValuePair(String name, String value) {
		return new BasicNameValuePair(name, value);
	}
	
	  /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
        	
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
            return "cc";
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


	public static HttpEntity postForHttpEntity(String url, Map<String, String> params) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter("http.protocol.content-charset",
				HTTP.UTF_8);
		httpClient.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
		httpClient.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
		httpClient.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,
				HTTP.UTF_8);
		HttpPost post = new HttpPost(url);
		if (params != null && !params.isEmpty()) {
			UrlEncodedFormEntity formEntity = null;
			List<NameValuePair> postParams = new ArrayList<NameValuePair>();
			for (String paramName : params.keySet()) {
				postParams.add(HttpUtils.basicNameValuePair(paramName,
						params.get(paramName)));
			}

			try {
				formEntity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			post.setEntity(formEntity);
		}
		System.out.println("request URL " + post.getURI());

		BasicHttpResponse response;
		try {
			response = (BasicHttpResponse) httpClient.execute(post);
			return response.getEntity();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

	public static JSONObject postForJson(String url, Map<String, String> params) {
		try {
			URLConnection connection = new URL(url).openConnection();
			connection.setDoOutput(true);
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "8859_1");
			out.write(""); // 向页面传递数据。post的关键所在！
			out.flush();
			out.close();
			String sCurrentLine;
			String sTotalString = "";
			BufferedReader l_reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			while ((sCurrentLine = l_reader.readLine()) != null) {
				sTotalString += sCurrentLine;
			}
			return JSONObject.fromObject(sTotalString);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		System.out.println("1".equals(String.valueOf(1L)));
	}

}
